import maphandler
import pygame
import xml.sax

class Tile(pygame.sprite.Sprite):
	def __init__(self, tileImage):
		pygame.sprite.Sprite.__init__(self)
		self.image = tileImage
		self.rect = self.image.get_rect()
	def Draw(self, screen, (x, y)):
		screen.blit(self.image, (x, y))

class Map:
	def __init__(self, xmlPath):
		parser = xml.sax.make_parser()
		handler = maphandler.MapHandler()

		parser.setContentHandler(handler)
		parser.parse(xmlPath)

		self.tile_key = handler.tile_key
		self.tile_map = handler.map
		self.passable = handler.passable
		self.tiles = self.tile_map
		
		# Load sprites into self.sprites
		sprites = {}
		for i in self.tile_key:
			buffimage = pygame.image.load(self.tile_key[i])
			sprites[i] = buffimage.convert()
		self.sprites = sprites
		
		# Iterate over the tiles and replace the key with a Tile object
		for x in range(len(self.tiles)):
			for y in range(len(self.tiles[x])):
				tile_id = self.tiles[x][y]
				self.tiles[x][y] = Tile(self.sprites[tile_id])
				self.tiles[x][y].passable = self.passable[tile_id]
		
		# Assuming all tiles are the same width and height as the first
		self.tile_width = self.tiles[0][0].rect.width
		self.tile_height =self.tiles[0][0].rect.height

	# DrawMap draws a tile map on the surface parameter, screen. 
	def Draw(self, screen):
		for y in range(len(self.tiles)):
			current_line = self.tiles[y]
			for x in range(len(current_line)):
				current_tile = current_line[x]
				current_tile.Draw(screen, (x*self.tile_width , y*self.tile_height))
				
	def GetImpassableRectangles(self):
		rects = []
		for y in range(len(self.tiles)):
			current_line = self.tiles[y]
			for x in range(len(current_line)):
				current_tile = current_line[x]
				if current_tile.passable is False:
					rects.append(current_tile.rect.move(x*self.tile_width, y*self.tile_height))
		return rects